import { signal, computed } from "@preact/signals";
import { settings } from "./settings";
import { isStarts } from "./utilities";

const key = "lemon_daisy_history";
const stor = globalThis.localStorage;

const sorters = [
  /* 时间升序 */
  (a, b) => a.time - b.time,
  /* 时间降序 */
  (a, b) => b.time - a.time,
  /* 次数升序 */
  (a, b) => a.count - b.count,
  /* 次数降序 */
  (a, b) => b.count - a.count,
  /* 次数升序 时间升序 */
  (a, b) => (b.count === a.count ? a.time - b.time : a.count - b.count),
  /* 次数升序 时间降序 */
  (a, b) => (b.count === a.count ? b.time - a.time : a.count - b.count),
  /* 次数降序 时间升序 */
  (a, b) => (b.count === a.count ? a.time - b.time : b.count - a.count),
  /* 次数降序 时间降序 */
  (a, b) => (b.count === a.count ? b.time - a.time : b.count - a.count),
];

export const sortersName = [
  "时间升序",
  "时间降序",
  "次数升序",
  "次数降序",
  "次数升序 时间升序",
  "次数升序 时间降序",
  "次数降序 时间升序",
  "次数降序 时间降序",
];

export const sortHistory = computed(
  () => sorters[settings.value.searchPart.historySorter],
);

export const histories = signal([]);

export function getSortedHistories(word) {
  return histories.value
    .filter((object) =>
      isStarts(
        object.content,
        word,
        !settings.value.searchPart.caseInsensitive,
      ),
    )
    .toSorted(sortHistory.value)
    .map((hist) => hist.content);
}

export function clearHistory() {
  delete stor[key];
  histories.value = [];
}

export function initHistory() {
  if (stor[key]?.startsWith("[")) {
    histories.value = [...JSON.parse(stor[key])];
  } else {
    clearHistory();
  }
}

function store(data) {
  stor[key] = JSON.stringify(data);
  histories.value = data;
}

const findFunction = (content, object) => object.content === content;

export function addHistory(content) {
  const Hist = structuredClone(histories.value);
  const item = Hist.find((data) => findFunction(content, data));
  const index = item
    ? Hist.findIndex((data) => findFunction(content, data))
    : Hist.length;
  Hist[index] = {
    content,
    time: Date.now(),
    count: 1 + (item?.count ?? 0),
  };
  store(Hist);
}

export function delHistory(content) {
  const Hist = structuredClone(histories.value);
  const item = Hist.findIndex((data) => findFunction(content, data));
  Hist.splice(item, 1);
  histories.value = Hist;
  if (Hist.length === 0) {
    delete stor[key];
  } else {
    stor[key] = JSON.stringify(Hist);
  }
}

const formatter = new Intl.DateTimeFormat("zh-CN", {
  dateStyle: "full",
  timeStyle: "medium",
  timeZone: "Asia/Shanghai",
});

export function exportHistory() {
  let csv = "搜索词,搜索次数,时间,时间戳\n";
  for (const object of JSON.parse(stor[key]).toSorted(sortHistory.value)) {
    csv += `"${object.content}",${String(object.count)},${formatter.format(new Date(object.time))},${String(object.time)}\n`;
  }
  return csv;
}

export function importHistories(data, merge) {
  let result = data;
  const current = structuredClone(histories.value);
  if (merge) {
    result = [
      ...current,
      ...data.filter(
        (item) => !current.some((data) => findFunction(item.content, data)),
      ),
    ];
  }
  store(result);
}
